<template>
    <div class="homepage-container">
        <div class="stats">
            <template v-if="isAdmin">
                <div class="stat-card" v-for="item in statcardList">
                    <div>{{ item.title }}</div>
                    <div class="bottomnum">
                        <div class="num">{{ item.num }}</div>
                        <!-- <el-icon size="35" style="margin-right: 20px;">
                            <component :is="item.icon" />
                        </el-icon> -->
                        <!-- <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35" viewBox="0 0 24 24">
                            <path fill="currentColor" fill-rule="evenodd" :d="item.icon" clip-rule="evenodd" />
                        </svg> -->
                        <!-- <span>
                            {{ item.icon }}
                        </span> -->
                        <img :src="item.icon" alt="" style="width: 35px;height: 35px;">
                    </div>
                </div>
            </template>
            <template v-else>
                <div class="stat-card carddis" v-for="item in statcardListDistributor">
                    <div>{{ item.title }}</div>
                    <div class="bottomnum">
                        <div class="num">{{ item.num }}</div>
                        <!-- <el-icon size="35" style="margin-right: 20px;">
                            <component :is="item.icon" />
                        </el-icon> -->
                        <img :src="item.icon" alt="" style="width: 30px;height: 30px;">

                    </div>
                </div>
            </template>
        </div>
        <div style="display: flex;justify-content: space-between;margin-top: 20px;">
            <div class="bar" ref="barpic"></div>
            <div class="equipment-stats-card">
                <div class="stats-item" v-for="item in carddata">
                    <div class="stats-label">{{ item.title }}</div>
                    <div class="stats-value">{{ item.num }}</div>
                </div>
                <div class="revenue-line"></div>
            </div>
        </div>
        <div style="display: flex;justify-content: space-between;margin-top: 20px;">
            <div class="barpicHor" ref="barpicHor"></div>
            <!-- 饼形图 -->
            <div class="pie" ref="piepic"></div>
            <div class="systemlist">
                <div class="announcement-container">
                    <div class="announcement-header">
                        <div style="font-weight: bold;"><el-icon style="margin-right: 10px;">
                                <Tickets />
                                <!-- </el-icon>Unprocessed feedback records</div> -->
                            </el-icon>feedback records</div>
                        <el-link type="primary"
                            @click="() => { return router.push('/logsview/feedbackrecord') }">more</el-link>
                    </div>

                    <el-table :data="announcements" style="width: 100%" :show-header="false">
                        <el-table-column prop="feedbackTitle" label="标题">
                            <template #default="{ row }">
                                <el-link type="primary"
                                    style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;cursor: pointer;"
                                    :title="row.feedbackTitle"
                                    @click="() => { return router.push(`/logsview/feedbackrecord?feedbackId=${row.feedbackId}`) }">
                                    <!-- {{ row.feedbackTitle}} -->
                                    {{

                                        row.feedbackTitle && row.feedbackTitle.length > 10
                                            ? row.feedbackTitle.slice(0, 10) + '...'
                                            : row.feedbackTitle
                                    }}
                                </el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="日期" width="180" align="right">
                            <template #default="{ row }">
                                <span class="date-text">{{ row.createTime }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, ref, onBeforeUnmount, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { getFeedbackdata, getstatcardListdata, getstatcardListDistributordata } from '../../api/api';
import people from "../../assets/images/people.png"
import tianneibuhuoyueyonghu from "../../assets/images/tianneibuhuoyueyonghu.png"
import guanliyuan from "../../assets/images/guanliyuan.png"
import fenxiaoshang from "../../assets/images/fenxiaoshang.png"
import yonghu from "../../assets/images/yonghu.png"
import kucunshebei from "../../assets/images/kucunshebei.png"
import icontest from "../../assets/images/icon-test (3).png"
import jianceshebei from "../../assets/images/jianceshebei-lixianshuliang.png"
import zaixianshebei from "../../assets/images/zaixianshebei.png"
let router = useRouter();
defineOptions({
    name: 'HomePage'
})
const isAdmin = ref(false); 
// 获取环境变量
// const apiKey = import.meta.env.VITE_APP_GOOGLE_MAP_KEY;
// console.log(apiKey);    

onMounted(() => {
    getFeedback()
    const userRoles = JSON.parse(localStorage.getItem('userdetail'))?.roles || [];
    isAdmin.value = userRoles.some(role => role.roleName === 'admin' || role.roleName === 'SuperAdmin');
    // if (window.location.href.includes('/nop')) {
    if (!sessionStorage.getItem('hasInitialized')) {
        window.location.reload()
        sessionStorage.setItem('hasInitialized', 'true');
    }
    getbar()
    getbarHor()
    getpie()
    getstatcardList()
    getstatcardListDistributor()

})
onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    if (myChart) {
        myChart.dispose();
        myChart = null;
    }
});

// let isroles = ref(true)
// if (localStorage.getItem("routesData") == null) {
//     isroles = ref(false)
// } else {
//     isroles = ref(true)
// }
// 反馈
const announcements = ref()
async function getFeedback() {
    try {
        let data = await getFeedbackdata(1, 5)
        if (data.code == 200) {
            announcements.value = data.rows
        }
    } catch (error) {
        console.log(error);
    }
}
// 卡片
const carddata = ref([
    {
        id: 1,
        title: "Today's earnings (yuan)",
        num: "355,588"
    }, {
        id: 2,
        title: "Today's order quantity (single)",
        num: "355,588"
    }
])
// 头部
let statcardList = ref([])
let statcardListDistributor = ref([])
let endUserTotal = ref(null)
async function getstatcardList() {
    let res = await getstatcardListdata()
    if (res.code == 200) {
        endUserTotal.value = res.data.endUserTotal
        statcardList.value = [
            {
                id: 1,
                title: "Total number of users",
                num: res.data.userTotal,
                // icon: ''
                icon: people
            }, {
                id: 2,
                title: "Daily active users",
                num: res.data.dayActiveTotal,
                icon: tianneibuhuoyueyonghu
            }, {
                id: 3,
                title: "Administrators",
                num: res.data.adminUserTotal,
                icon: guanliyuan
            }, {
                id: 4,
                title: "Distributor",
                num: res.data.disUserTotal,
                icon: fenxiaoshang
            }, {
                id: 5,
                title: "End User",
                num: res.data.endUserTotal,
                icon: yonghu

            }
        ]
    }
}
async function getstatcardListDistributor() {
    let res = await getstatcardListDistributordata()
    if (res.code == 200) {
        statcardListDistributor.value = [
            {
                id: 5,
                title: "End User",
                num: endUserTotal.value,
                icon: yonghu
            }, {
                id: 6,
                title: "Quantity of inventory equipment",
                num: res.data.inventoryEquipmentTotal,
                icon: kucunshebei
            }, {
                id: 7,
                title: "Number of terminal devices",
                num: res.data.endUserEquipmentTotal,
                icon: icontest
            }, {
                id: 8,
                title: "Number of devices online",
                num: res.data.onlineEquipmentTotal,
                icon: zaixianshebei
            }, {
                id: 9,
                title: "Number of offline devices",
                num: res.data.offlineEquipmentTotal,
                icon: jianceshebei
            }
        ]
    }
}
// ----------------柱状图-----------------
// 获取柱状图
let barpic = ref(null)
let myChart = null;
let bartitle = ref(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
let baroneclass = ref([120, 200, 150, 80, 70, 110, 130, 150, 20, 40, 140, 248])
// let bartwoclass = ref([120, 200, 150, 80, 70, 110, 130],)
// let barthreeclass = ref([120, 200, 150, 80, 70, 110, 130],)
let yearordata = ref(true)
async function getbar() {
    window.addEventListener('resize', handleResize);
    // 检查是否已有实例
    if (myChart) {
        myChart.dispose(); // 销毁旧实例
    }
    // 确保 DOM 已绑定
    if (!barpic.value) return;
    // 初始化完毕开始获取dom
    myChart = echarts.init(barpic.value);
    const option = {
        backgroundColor: '#f8faff', /* 极浅蓝灰背景 */
        title: {
            text: `${yearordata.value ? 'Annual income amount ' : 'Monthly income amount '}`
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
        },
        toolbox: {
            feature: {
                myCustomButton: {
                    show: true,
                    title: 'Change to month or year', // 鼠标悬停提示
                    icon: 'path://M768 256v192h-128v-192h128zM256 768v-192h128v192h-128zM512 128c-212.8 0-384 171.2-384 384s171.2 384 384 384 384-171.2 384-384h-64c0 176-144 320-320 320s-320-144-320-320 144-320 320-320c85.6 0 164.8 33.6 224 89.6l-89.6 89.6h256v-256l-83.2 83.2c-76.8-76.8-182.4-124.8-300.8-124.8z',
                    onclick: function () {
                        yearordata.value = !yearordata.value
                        if (!yearordata.value) {
                            // 获取当前日期
                            const now = new Date();
                            // 获取当前月份（1-12）
                            const currentMonth = now.getMonth() + 1;
                            // 获取当前年份
                            const currentYear = now.getFullYear();
                            // 计算当月天数
                            function getDaysInMonth(year, month) {
                                return new Date(year, month, 0).getDate();
                            }
                            const daysInMonth = getDaysInMonth(currentYear, currentMonth);
                            // console.log(`当前是${currentMonth}月，共有${daysInMonth}天`);
                            bartitle.value = []
                            baroneclass.value = []
                            for (var i = 1; i <= +daysInMonth; i++) {
                                bartitle.value.push(i + "th")
                                baroneclass.value.push(parseInt(Math.random() * 1000))
                            }
                            getbar()
                        } else {
                            bartitle.value = []
                            for (var i = 1; i <= 12; i++) {
                                bartitle.value.push(i + "month")
                            }
                            baroneclass.value = [120, 200, 150, 80, 70, 110, 130, 150, 20, 40, 140, 248];
                            getbar()
                        }

                    }
                }
            }
        },
        grid: {
            left: '3%',
            right: '0%',
            bottom: '3%',
            containLabel: true,
            borderColor: '#e2e8f0',
        },
        xAxis: {
            type: 'category',
            data: bartitle.value,
        },
        yAxis: {
            type: 'value',
            axisLine: {
                show: true
            },
        },
        series: [
            {
                name: 'income',
                type: 'bar',
                stack: 'total',
                barWidth: '30%',
                data: baroneclass.value,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#4a80f0' }, /* 科技蓝渐变 */
                        { offset: 1, color: '#6ba1ff' }
                    ])
                }
            },
        ]
    }
    // 加载效果
    myChart.showLoading();
    //  let {data} = await getbarpic()
    //  if(data.code == 200){
    //     data.data.forEach(item => {
    //    bartitle.value.push(item.title)
    //    baroneclass.value.push(item.oneclass)
    //    bartwoclass.value.push(item.twoclass)
    //    barthreeclass.value.push(item.threeclass)
    //     });
    //     // // 重新调用echarts
    myChart.setOption(option);
    //     // // 去除加载效果
    myChart.hideLoading();
    //  }
    // myChart.setOption(option);
}

// ---------------------
// --------------横向柱状图---------
let barpicHor = ref(null)
let myChartHor = null;
let daytitle = ref(["11th", "12th", "13th", "14th", "15th", "16th", "17th"])
let daymoney = ref([150, 290, 180, 60, 110, 180, 50])
async function getbarHor() {
    window.addEventListener('resize', handleResize);
    // 检查是否已有实例
    if (myChartHor) {
        myChartHor.dispose(); // 销毁旧实例
    }
    // 确保 DOM 已绑定
    if (!barpicHor.value) return;

    // 初始化完毕开始获取dom
    myChartHor = echarts.init(barpicHor.value);
    let optionHor = {
        backgroundColor: '#f8faff', /* 极浅蓝灰背景 */
        title: {
            // text: '近七日收益金额'
            text: 'Income amount in the past seven days'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {},
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
            borderColor: '#e2e8f0',
        },
        xAxis: {
            axisLine: {
                show: true
            },
            type: 'value',
            data: bartitle.value
        },
        yAxis: {
            type: 'category',
            axisLine: {
                show: true
            },
            data: daytitle.value
        },
        series: [
            {
                // name: '收益',
                type: 'bar',
                data: daymoney.value,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#4a80f0' }, /* 科技蓝渐变 */
                        { offset: 1, color: '#6ba1ff' }
                    ])
                }
            }
        ]
    }
    // 加载效果
    myChartHor.showLoading();
    //  let {data} = await getbarpic()
    //  if(data.code == 200){
    //     data.data.forEach(item => {
    //    bartitle.value.push(item.title)
    //    baroneclass.value.push(item.oneclass)
    //    bartwoclass.value.push(item.twoclass)
    //    barthreeclass.value.push(item.threeclass)
    //     });
    //     // // 重新调用echarts
    myChartHor.setOption(optionHor);
    //     // // 去除加载效果
    myChartHor.hideLoading();
    //  }
    // myChart.setOption(option);
}
// ----------------------------------------
// -----------------------饼形图--------------
// 获取饼形图  
let piepic = ref(null)
// let dataarr = ref([])
let myChartpie = null
async function getpie() {
    window.addEventListener("resize", handleResize)
    if (myChartpie) {
        myChartpie.dispose()
    }
    // 初始化完毕开始获取dom
    myChartpie = echarts.init(piepic.value);
    let optionpie = {
        color: ['#2ec7c9', '#b6a2de', '#b3c2ff', '#ffcb8c', '#d87a80', "#34bfa3"],
        backgroundColor: '#f8faff', /* 极浅蓝灰背景 */
        title: {
            // subtext: 'Fake Data',
            left: 'center'
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '5%',
            left: 'center'
        },
        series: [
            {
                name: '',
                type: 'pie',
                center: ['50%', '60%'],
                radius: '50%',
                data: [
                    { value: 1048, name: 'PowerTank' },
                    { value: 735, name: 'PowerEden' },
                    { value: 580, name: 'PowerWhale' },
                    { value: 484, name: 'PowerPico' },
                    { value: 300, name: 'PowerFarm' },
                    { value: 200, name: 'PowerChill' }
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    }

    // 加载效果
    myChartpie.showLoading();
    // let { data } = await getpiepic()
    // if (data.code == 200) {
    //     data.data.forEach(item => {
    //         dataarr.value.push({
    //             value: item.value,
    //             name: item.name
    //         })
    //     });
    // 重新调用echarts
    myChartpie.setOption(optionpie);
    //     // 去除加载效果
    myChartpie.hideLoading();
    // }
}
// ------------------------------------
function handleResize() {
    if (myChart) {
        myChart.resize();
    }
    if (myChartHor) {
        myChartHor.resize();
    }
    if (myChartpie) {
        myChartpie.resize();
    }
}
</script>

<style scoped lang="scss">
.homepage-container {
    padding: 20px;

    .stats {
        // display: flex;
        // gap: 20px;
        display: flex;
        // flex-wrap: wrap;
        gap: 20px;

        .stat-card {
            // color: #fff;
            // height: 100px;
            // padding: 25px;
            // background: #f8f9fa;
            // /* 浅灰色边框 */
            // border-radius: 4px;
            // box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            // flex: 1;
            overflow: hidden; // 防止内容溢出
            white-space: nowrap; // 禁止文字换行
            text-overflow: ellipsis; // 文字过长时显示省略号
            color: #fff;
            height: 100px;
            padding: 25px;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            flex: 1 1 100px; // 基础宽度200px，允许收缩（flex-shrink:1）
            min-width: 100px;

            .bottomnum {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top: 10px;

                .num {
                    margin: 14px 0;
                    font-size: 30px;
                    font-weight: bold;
                }
            }
        }

        /* 不同卡片可微调颜色 */
        .stat-card:nth-child(1) {
            background: linear-gradient(to bottom, #4e73df 0%, #86a8e7 100%);
        }

        .stat-card:nth-child(2) {
            // background-color: #1cc88a;
            background: linear-gradient(to bottom, #1cc88a 0%, #5eebc4 100%);
        }

        .stat-card:nth-child(3) {
            // background-color: #f6c23e;
            background: linear-gradient(to bottom, #f6c23e, #edd17e);
        }

        .stat-card:nth-child(4) {
            // background-color: #ff6b6b;
            background: linear-gradient(to bottom, #ff6b6b, #ff8f8f);
        }

        .stat-card:nth-child(5) {
            // background-color: #9b5de5;
            background: linear-gradient(to bottom, #9b5de5, #b388f0);
        }

        .carddis:nth-child(1) {
            background: linear-gradient(to bottom, #9b5de5, #b388f0);
        }

        .carddis:nth-child(2) {
            background: linear-gradient(to bottom, #a9bd70, #c7d985);
        }

        .carddis:nth-child(3) {
            background: linear-gradient(to bottom, #8ab45c, #a7cd6f);
        }

        .carddis:nth-child(4) {
            background: linear-gradient(to bottom, #78a860, #95c275);
        }

        .carddis:nth-child(5) {
            background: linear-gradient(to bottom, #5a9a4a, #7db35a);
        }
    }

    .bar {
        width: 75%;
        height: 300px;
        background-color: #fff;
        box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
    }



    .equipment-stats-card {
        width: 20%;
        padding: 20px;
        height: 240px;
        margin-top: 20px;
        border-radius: 10px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        background: linear-gradient(135deg, #e2e8f0 0%, #f1f5f9 50%);
        border: 1px solid #e2e8f0;
        box-shadow:
            0 2px 4px rgba(0, 0, 0, 0.02),
            inset 0 -2px 0 #4a80f0;
        /* 底部蓝光晕 */
    }

    .stats-item {
        margin: 10px 0;
        padding: 10px 0;
    }

    .stats-label {
        font-size: 14px;
        color: #666;
    }

    .stats-value {
        font-size: 35px;
        color: #333;
        text-align: center;
        margin-top: 15px;
    }

    .revenue-line {
        height: 1px;
        background-color: #eaeaea;
        margin: 10px 0;
    }

    .barpicHor {
        width: 40%;
        height: 300px;
        // background-color: #fff;
    }

    .pie {
        width: 28%;
        height: 300px;
    }

    .systemlist {
        width: 28%;
        height: 300px;
        overflow: hidden;
        background-color: #fff;

        .el-link {
            color: #000;
        }

        .announcement-container {
            height: 258px;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
        }

        .announcement-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .announcement-header h3 {
            margin: 0;
            font-size: 16px;
            font-weight: normal;
        }

        .date-text {
            color: #999;
            font-size: 14px;
        }

        .el-table::before {
            height: 0;
        }

        .el-table {
            --el-table-border-color: transparent;
        }
    }
}
</style>